<template>
<div class="blog-carousel" v-if="slides.length>2">
   <div class="carousel-container"
       @mouseenter="pauseAutoPlay"
       @mouseleave="startAutoPlay"
       :style="containerHeight">
    <!-- 轮播内容 -->
    <div class="carousel-track">
      <div
        v-for="(item, index) in slides"
        :key="index"
        class="carousel-item"
        :class="{ active: currentIndex === index, 'has-loaded': item.loaded }"
      >
        <img
          v-if="item.loaded && item.is_enable_url"
          :src="item.url"
          :alt="item.name"
          @load="updateContainerHeight">
        <img
          v-else
          :src="item.image"
          :alt="item.name"
          @load="updateContainerHeight">
        <div class="carousel-caption">
          <p> {{ item.name }} </p>
        </div>
          <div v-if="slides.length === 0" class="loading-state">
  加载中...
</div>
      </div>
    </div>

    <!-- 导航箭头 -->
    <button class="carousel-prev" @click="prevSlide">‹</button>
    <button class="carousel-next" @click="nextSlide">›</button>

    <!-- 指示器 -->
    <div class="carousel-indicators">
      <button
        v-for="(item, index) in slides"
        :key="index"
        :class="{ active: currentIndex === index }"
        @click="goToSlide(index)"
      ></button>
    </div>
  </div>
  <div class="banner-container">
    <div class="banner-content" v-for="(item, index) in banners" :key="index">
      <img :src="item.url" alt="{{item.name}}" v-if="item.is_enable_url">
      <img :src="item.image" alt="{{item.name}}" v-else>
      <p>{{ item.name }}</p>
    </div>
  </div>
</div>
</template>

<script setup>
const slides = ref([])
const banners = ref([])
const currentIndex = ref(0)
const loop = ref(true)
const container = ref(null)
const containerHeight = ref('')
const autoPlay = ref(true)
let timer = null

const trackStyle = computed(() => ({
  transform: `translateX(-${currentIndex.value * 100}%)`
}))

function nextSlide() {
  if (loop.value || currentIndex.value < slides.value.length - 1) {
    currentIndex.value = (currentIndex.value + 1) % slides.value.length
  }
}

function prevSlide() {
  currentIndex.value = (currentIndex.value - 1 + slides.value.length) % slides.value.length
}

function goToSlide(index) {
  currentIndex.value = index
}

function startAutoPlay() {
  if (autoPlay.value) {
    timer = setInterval(() => {
      nextSlide()
    }, 3000)
  }
}

function pauseAutoPlay() {
  clearInterval(timer)
}

watch(currentIndex, async (newIndex) => {
  if (slides.value[newIndex] && !slides.value[newIndex].loaded) {
    slides.value[newIndex].loaded = true;
  }
  await nextTick();
  updateContainerHeight();
});

function updateContainerHeight() {
  const activeItem = container.value?.querySelector('.carousel-item.active')
  if (activeItem) {
    containerHeight.value = `height: ${activeItem.clientHeight}px`
  }
}

async function fetchSlides() {
  try {
    const response = await axios.get('/api/blog/carousel/');
    const data = response.data.results;

    if (Array.isArray(data)) {
      slides.value = data
        .filter(item => item.is_show) // 仅使用 is_show 为 true 的项
        .map(item => ({
          image: item.image, // 使用 API 的 image 字段
          name: item.name, // 使用 API 的 name 字
          url: item.url, // 使用 API 的 url 字段
          is_enable_url: item.is_enable_url, // 使用 API 的 is_enable_url 字段
          loaded: false, // 初始化懒加载状态
        }));
    } else {
      console.error('Invalid response format');
    }
  } catch (error) {
    console.error('Error fetching carousel data:', error);
  }
}
const fetchBanners = async () => {
  try {
    const response = await axios.get('/api/blog/carousel/random/')
    banners.value = response.data
  } catch (error) {
    console.error('获取轮播图失败:', error)
  }
}


onMounted(() => {
  fetchSlides();
  fetchBanners();
  startAutoPlay();
});

onBeforeUnmount(() => {
  clearInterval(timer);
})
</script>


<style scoped>
  .blog-carousel {
  width: 100%;
  margin:0 auto 10px auto;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.banner-container {
  width: 30%;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;  /* 控制广告项间距 */
}

.banner-content {
  position: relative;
  background: white;
  overflow: hidden;
  border-radius: 8px;
  width: 100%;
  height: 126px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.banner-content img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.banner-content p {
 position: absolute;
  top: 40%;
  left: 50%;
  transform: translateX(-50%);
  color: var(--blog-carousel-caption-color, #fff);
  text-align: center;
  width: calc(100% - 25px);
}
.carousel-container {
  float: left;
  position: relative;
  width: 70%;
  height: 400px;
  overflow: hidden;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.carousel-track {
  display: flex;
  transition: transform 0.5s ease;
}

.carousel-item {
  flex: 0 0 100%;
  position: relative;
  height: 100%;
}

.carousel-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-caption {
  position: absolute;
  bottom: 50%;
  left: 50%;
  transform: translateX(-50%);
  color: var(--blog-carousel-caption-color, #fff);
  text-align: center;
}

.carousel-prev,
.carousel-next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  color: var(--blog-carousel-control-color, #fff);
  border: none;
  padding: 15px 20px;
  cursor: pointer;
}

.carousel-prev {
  left: 10px;
  font-size: 32px;
}

.carousel-next {
  right: 10px;
  font-size: 32px;
}

.carousel-indicators {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 5px;
}

.carousel-indicators button {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: none;
  background: rgba(255,255,255,0.5);
  cursor: pointer;
}

.carousel-indicators .active {
  background: rgba(255,255,255,0.9);
}
  /* 新增淡入淡出动画 */
.carousel-item {
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
  position: absolute;
  width: 100%;
}

.carousel-item.active {
  opacity: 1;
}

/* 自适应高度过渡 */
.carousel-container {
  transition: height 0.3s ease-in-out;
}

/* 懒加载相关样式 */
.carousel-item:not(.has-loaded) {
  background: #f0f0f0;
}

@media (max-width: 992px) {
  .blog-carousel {
  flex-direction: column;}
  .carousel-container {
    width: 100%;
  }
  .banner-container {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
    margin-left: 0;
    margin-top: 10px;
  }
}
  @media (max-width: 576px) {
   .banner-container{
      flex-direction: column;
      align-items: center;
     justify-content: center;
     height: auto;
   }
  }
@media (max-width: 480px) {
  .carousel-container {
    height: 200px;
  }
  .banner-container{
      display: none;
   }
}
</style>
